package alert

import (
	"context"

	"yunzhan/alert-server/internal/svc"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteAlertRuleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewDeleteAlertRuleLogic 删除告警规则
func NewDeleteAlertRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteAlertRuleLogic {
	return &DeleteAlertRuleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteAlertRuleLogic) DeleteAlertRule(req *types.DeleteAlertRuleRequest) (resp *types.DeleteAlertRuleResponse, err error) {
	var deletedRules []*types.AlertRule

	for _, id := range req.ID {
		// 查找要删除的规则
		rule, err := l.svcCtx.AlertRuleModel.FindOne(id)
		if err != nil {
			logx.Errorf("failed to find alert-server rule with id %d: %v", id, err)
			return &types.DeleteAlertRuleResponse{
				Success: 0,
				Message: "Failed to find alert-server rule",
				Error:   err.Error(),
			}, err
		}

		// 删除规则
		err = l.svcCtx.AlertRuleModel.Delete(id)
		if err != nil {
			logx.Errorf("failed to delete alert-server rule with id %d: %v", id, err)
			return &types.DeleteAlertRuleResponse{
				Success: 0,
				Message: "Failed to delete alert-server rule",
				Error:   err.Error(),
			}, err
		}

		// 添加到已删除的规则列表
		deletedRules = append(deletedRules, rule)
	}

	// 返回删除成功的详细信息
	return &types.DeleteAlertRuleResponse{
		Success:      1,
		Message:      "Alert rule(s) deleted successfully",
		DeletedRules: deletedRules,
	}, nil
}
